﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace CYTS.Aoyou.Framework.Utility
{
    /// <summary>
    /// DB转换帮助类
    /// </summary>
    public static class DBConvertHelper
    {
        /// <summary>
        /// 获取DataTable中的所有数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataTable"></param>
        /// <param name="generator"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetList<T>(this DataTable dataTable, Func<DataRow, T> generator)
        {
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                var dataRow = dataTable.Rows[i];
                yield return generator(dataRow);
            }
        }

        /// <summary>
        /// 获取DataRow中的数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataRow"></param>
        /// <param name="generator"></param>
        /// <returns></returns>
        public static T GetFirst<T>(this DataRow dataRow, Func<DataRow, T> generator)
        {
            if (dataRow != null)
            {
                return generator(dataRow);
            }
            else
            {
                return default(T);
            }
        }

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="reader"></param>
        ///// <param name="generator"></param>
        ///// <returns></returns>
        //public static IEnumerable<T> GetList<T>(this IDataReader reader, Func<IDataRecord, T> generator)
        //{
        //    while (reader.Read())
        //    {
        //        yield return generator(reader);
        //    }
        //}

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="reader"></param>
        ///// <param name="generator"></param>
        ///// <returns></returns>
        //public static T GetModel<T>(this IDataReader reader, Func<IDataReader, T> generator)
        //{
        //    if (reader.Read())
        //    { return generator(reader); }
        //    else
        //    { return default(T); }
        //}
    }
}
